package nl.altenpts.net;

/**
 * This class implements a scheduled task. 
 * @author fabian
 *
 */
public class ScheduledTask implements Comparable<ScheduledTask> {
	
	/**
	 * Construct a ScheduledTask which will execute task at when. If and only 
	 * if thread is true then the task is to be executed in a separate thread.
	 *   
	 * @param when Unix time in milliseconds
	 * @param task task
	 * @param thread Whether the task needs to be executed in a separate thread.
	 */
	ScheduledTask(long when, Runnable task, boolean thread) {
		this.when = when;
		this.task = task;
		this.thread = thread;
	}
	
	/**
	 * Construct a ScheduledTask which will execute task at when. The task
	 * is not executed in a separate thread. 
	 * 
	 * @param when Unix time in milliseconds
	 * @param task the task
	 */	
	ScheduledTask(long when, Runnable task) {
		this(when, task, false);
	}	
		
	/**
	 * Sorts tasks based on the time. Tasks that need to be executed
	 * earlier are sorted before tasks that need to be executed later.
	 * 
	 * @param the other task
	 */
	public int compareTo(ScheduledTask task) {
		return Long.signum(when - task.when);
	}
	
	/**
	 * Returns true if and only if this task must be executed in a separate
	 * thread. 
	 * 
	 * @return Whether the task is to be executed in a separate thread.
	 */
	public boolean isThreaded() {
		return thread;
	}
	
	/**
	 * Returns the task.
	 * 
	 * @return The task.
	 */
	public Runnable getTask() {
		return task;
	}
	
	/**
	 * Returns when this task is to be executed in Unix time.
	 * @return when this task is to be executed
	 */
	public long when() {
		return when;
	}
	
	/**
	 * Returns over how many milliseconds this task is to be executed. 
	 * 
	 * @return Over how many milliseconds this task is to be executed. 
	 */
	public long over() {
		return when - System.currentTimeMillis();
	}
	
	private long when;
	private Runnable task;
	private boolean thread;
}
